"use client";
import { useState, useMemo, useEffect } from "react";
import { Suspense } from 'react';
import { API_CONFIG } from "../../url"

interface InvoiceItem {
  xh: string;
  hsbz: string;
  spmc: string;
  je: string;
  sl: string;
  se: string;
  spbm: string;
  fphxz: string;
}

interface TaxInfo {
  id: string;
  stuId: string;
  sid: string;
  qdfphm: string;
  kplx: string;
  ykprq: string;
  ewmurl: string;
  // 其他可能的税务信息字段
}

function InvoiceForm() {
  const [userId, setUserId] = useState<string | null>(null);
  const [taxInfo, setTaxInfo] = useState<TaxInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 新增：下载弹窗相关状态
  const [isDownloadModalOpen, setIsDownloadModalOpen] = useState(false);
  const [downloadUrl, setDownloadUrl] = useState<string | null>(null);
  // 跟踪是否有可下载的发票
  const [hasDownloadableInvoice, setHasDownloadableInvoice] = useState(false);

  // 主表单状态
  const [formData, setFormData] = useState({
    ghdwdz: "",
    ghdwmc: "",
    kplx: "",
    hjse: "",
    ghdwyh: "",
    ghdwzh: "",
    xhdwdh: "010-68814900",
    gmf_dzyx: "",
    kpr: "",
    hjje: "",
    ghdwdh: "",
    fplxdm: "",
    ghdwsbh: "",
    bz: "",
    gfxxconfirm: "",
    jshj: "",
    xhdwyh: "中国农业银行股份有限公司北京古城支行",
    zyspmc: "",
    tspz: "",
    xhdwzh: "11031301040052826",
    xh: "1",
    fphxz: "0",
    hsbz: "1", // 默认含税
    yhzcbs: "",
    jshjdx: "",
    spmc: "培训费",
    je: "2298",
    sl: "0.01",
    se: "",
    spbm: "307020102",
    dj: "",
  });

  // 发票行项目
  const [invoiceItems, setInvoiceItems] = useState<InvoiceItem[]>([
    {
      xh: "1",
      hsbz: "1",
      spmc: "*非学历教育服务*培训费",
      je: "2298",
      sl: "0.01",
      se: "",
      spbm: "",
      fphxz: "0",
    }
  ]);

  // 其他状态
  const [isSuccessModalOpen, setIsSuccessModalOpen] = useState(false);
  const [successData, setSuccessData] = useState<any>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const [qrCodeBase64, setQrCodeBase64] = useState("");

  // 新增：下载提示信息状态
  const [downloadMessage, setDownloadMessage] = useState("您有已开可下载的发票"); // 初始值

  // 在状态管理部分添加新的状态
  const [isAlertOpen, setIsAlertOpen] = useState(false);
  const [alertMessage, setAlertMessage] = useState("");
  const [token, setToken] = useState<string | null>(null);

  // 从localStorage获取userId和token
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const storedToken = localStorage.getItem('token');
      const storedUserId = localStorage.getItem('userId');

      if (storedToken) {
        setToken(storedToken);
      } else {
        // Token缺失，引导用户登录
        console.warn('Token缺失，请重新登录');
        // 这里可以添加重定向到登录页的逻辑
      }

      setUserId(storedUserId);
    }
  }, []);

  // 在API请求前验证Token有效性
  const validateToken = () => {
    if (!token) {
      throw new Error('认证失败，请重新登录');
    }
    // 可以添加Token过期验证逻辑
  };

  // 根据userId获取税务信息
  useEffect(() => {
    if (!userId) return;

    const fetchTaxInfo = async () => {
      try {
        setLoading(true);
        setError(null);

        const response = await fetch(`${API_CONFIG.BASE_URL}/api/tax/get`,
          {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
              stuId: userId,
              kplx: "0"
            }),
          });

        if (!response.ok) {
          throw new Error('获取税务信息失败');
        }

        const data = await response.json();
        setTaxInfo(data);

        // 检查ewmurl是否存在
        if (data.ewmurl) {
          setHasDownloadableInvoice(true);
          setDownloadUrl(data.ewmurl);
        } else {
          setHasDownloadableInvoice(false);
        }

        // 根据税务信息更新表单
        if (data) {
          setFormData(prev => ({
            ...prev,
            ghdwmc: data.ghdwmc || "",
            ghdwdh: data.ghdwdh || "",
            ghdwsbh: data.ghdwsbh || "",
            // 其他字段根据API响应更新
          }));

          // 新增：检查ewmurl是否存在
          if (data.ewmurl) {
            setDownloadUrl(data.ewmurl);
            setIsDownloadModalOpen(true);
          }
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : '获取税务信息失败');
      } finally {
        setLoading(false);
      }
    };

    fetchTaxInfo();
  }, [userId, token]);


  // 大写金额转换函数
  const toChineseNumber = (n: number) => {
    const fraction = ['角', '分'];
    const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    const unit = ['元', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿'];

    let num = Math.abs(n);
    let s = '';

    for (let i = 0; i < fraction.length; i++) {
      const digitValue = Math.floor(num * 10 * Math.pow(10, i)) % 10;
      s += (digit[digitValue] + fraction[i]).replace(/零./, '');
    }

    s = s || '整';
    num = Math.floor(num);

    for (let i = 0; i < unit.length && num > 0; i++) {
      s = digit[num % 10] + unit[i] + s;
      num = Math.floor(num / 10);
    }

    return s.replace(/(零.)*零元/, '元')
      .replace(/(零.)+/g, '零')
      .replace(/^整$/, '零元整');
  };

  // 计算合计金额
  const calculateTotals = () => {
    let totalAmount = 0;
    let totalTax = 0;

    invoiceItems.forEach(item => {
      const amount = parseFloat(item.je) || 0;
      const taxRate = parseFloat(item.sl) || 0;

      if (item.hsbz === "1") { // 含税
        const tax = amount * taxRate / (1 + taxRate);
        totalAmount += amount - tax;
        totalTax += tax;
      } else { // 不含税
        const tax = amount * taxRate;
        totalAmount += amount;
        totalTax += tax;
      }
    });

    setFormData(prev => ({
      ...prev,
      hjje: totalAmount.toFixed(2),
      hjse: totalTax.toFixed(2),
      se: totalTax.toFixed(2),
      jshj: (totalAmount + totalTax).toFixed(2),
      jshjdx: toChineseNumber(totalAmount + totalTax)
    }));
  };


  // 当发票行项目变化时重新计算
  useEffect(() => {
    calculateTotals();
  }, [invoiceItems]);

  // 处理输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  // 处理发票行项目变化
  const handleItemChange = (index: number, field: keyof InvoiceItem, value: string) => {

    setInvoiceItems(prev => {
      const newItems = [...prev];
      newItems[index] = { ...newItems[index], [field]: value };

      // 如果是金额或税率变化，重新计算税额
      if (field === 'je' || field === 'sl' || field === 'hsbz') {
        const amount = parseFloat(newItems[index].je) || 0;
        const taxRate = parseFloat(newItems[index].sl) || 0;

        if (newItems[index].hsbz === "1") { // 含税
          const tax = amount * taxRate / (1 + taxRate);
          newItems[index].se = tax.toFixed(2);
        } else { // 不含税
          const tax = amount * taxRate;
          newItems[index].se = tax.toFixed(2);
        }
      }

      return newItems;
    });
  };

  // 添加新行
  const addNewItem = () => {
    setInvoiceItems(prev => [
      ...prev,
      {
        xh: `${prev.length + 1}`,  // 使用当前长度+1作为新序号
        hsbz: prev[0]?.hsbz || "1",
        spmc: "*非学历教育服务*培训费",
        je: "2298",  // 默认金额
        sl: prev[0]?.sl || "0.06",
        se: "",
        spbm: "307020102",
        fphxz: "0",
      }
    ]);
  };

  // 删除行
  const removeItem = (index: number) => {
    if (invoiceItems.length <= 1) return;

    setInvoiceItems(prev => {
      const newItems = prev.filter((_, i) => i !== index);
      // 重新排序序号
      return newItems.map((item, i) => ({ ...item, xh: `${i + 1}` }));
    });
  };

  // 表单验证
  const formErrors = useMemo(() => ({
    ghdwmc: formData.ghdwmc.trim() === "",
    ghdwsbh: formData.ghdwsbh.trim() === "",
    fplxdm: formData.fplxdm.trim() === "",
    kplx: formData.kplx.trim() === "",
    items: invoiceItems.some(item => item.spmc.trim() === "" || item.je.trim() === "")
  }), [formData, invoiceItems]);

  const isFormValid = useMemo(() =>
    !Object.values(formErrors).some(error => error),
    [formErrors]
  );

  // 修改：新增必填项错误状态
  const [validationErrors, setValidationErrors] = useState<Record<string, boolean>>({
    ghdwmc: false,
    ghdwdh: false,
    ghdwsbh: false,
    fplxdm: false,
    kplx: false,
    kpr: false
  });

  // 修改：提交表单时的验证逻辑
  const validateForm = () => {
    const errors = {
      ghdwmc: formData.ghdwmc.trim() === "",
      ghdwdh: formData.ghdwdh.trim() === "",
      ghdwsbh: formData.ghdwsbh.trim() === "",
      fplxdm: formData.fplxdm.trim() === "",
      kplx: formData.kplx.trim() === "",
      kpr: formData.kpr.trim() === ""
    };

    setValidationErrors(errors);
    return !Object.values(errors).some(error => error);
  };


  // 开票接口
  const submitFormData1 = async () => {
    // 先验证表单
    if (!validateForm()) {
      setSubmitError('请填写所有必填字段');
      return;
    }

    setIsSubmitting(true);
    setSubmitError("");

    try {
      // 调试：打印关键数据
      console.log('formData:', formData);
      console.log('invoiceItems:', invoiceItems);
      console.log('token:', token);

      // 验证数据
      const validationErrors = [];
      if (!formData.ghdwmc) validationErrors.push('购方名称');
      if (!formData.ghdwdh) validationErrors.push('购方单位电话');
      if (!formData.ghdwsbh) validationErrors.push('购方税号');
      if (!formData.fplxdm) validationErrors.push('发票类型');
      if (!formData.kplx) validationErrors.push('开票类型');

      if (validationErrors.length > 0) {
        throw new Error(`必填字段缺失: ${validationErrors.join(', ')}`);
      }

      // 准备请求数据
      const requestData = {
        ...formData,
        invoiceItems: invoiceItems.map(item => ({
          ...item,
          je: parseFloat(item.je).toFixed(2),
          sl: parseFloat(item.sl).toFixed(4),
          se: parseFloat(item.se).toFixed(2)
        }))
      };

      console.log('提交数据:', JSON.stringify(requestData, null, 2));

      const response = await fetch(`${API_CONFIG.BASE_URL}/api/invoice?stuId=${userId}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(requestData)
      });

      const result = await response.json();
      console.log('API响应:', result);

      if (!response.ok || result.code !== "00000") {
        throw new Error(result.msg || '发票开具失败');
      }

      // 处理成功响应
      setSuccessData({
        fphm: result.data.fphm,
        kprq: result.data.kprq,
        pdfUrl: result.data.pdf_url,
        ofdUrl: result.data.ofd_url,
        ewmUrl: result.data.ewm_url
      });
      setIsSuccessModalOpen(true);
    } catch (error) {
      console.error('开票失败:', error);
      setSubmitError(
        error instanceof Error
          ? error.message
          : '发票开具失败，请检查数据后重试'
      );
    } finally {
      setIsSubmitting(false);
    }
  };
  // 下载处理
  const handleDownload = (url: string, type: string) => {
    // 直接在新标签页打开下载链接
    window.open(url, '_blank');
  };
  const handleViewQrCode = (url: string) => {
    // 直接在新标签页打开二维码
    window.open(url, '_blank');
  };

  // 处理ewmurl下载
  const handleEwmUrlDownload = () => {
    if (downloadUrl) {
      setIsDownloadModalOpen(true);
      setDownloadMessage('查看电子票二维码'); // 设置下载消息
    }
  };

  // 二维码弹窗关闭时的回调
  const handleQrCodeClose = async () => {
    setQrCodeBase64(""); // 关闭弹窗
    // 二维码扫描完成后调用开票接口
    // await submitFormData();
  };

  // 创建提示弹窗组件
  const AlertModal = () => (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 animate-fadeIn">
      <div className="bg-white p-8 rounded-xl shadow-2xl max-w-md w-full mx-4 border border-gray-100 animate-scaleIn">
        <div className="text-center space-y-6">
          <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-blue-100">
            <svg
              className="h-6 w-6 text-blue-600"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth="2"
                d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
              />
            </svg>
          </div>
          <h3 className="text-xl font-bold text-gray-800">温馨提示</h3>
          <p className="text-gray-600">{alertMessage}</p>
          <div className="pt-4 flex justify-center">
            <button
              onClick={() => setIsAlertOpen(false)}
              className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors duration-200"
            >
              我知道了
            </button>
          </div>
        </div>
      </div>
    </div>
  );
  // 新增：下载发票弹窗组件
  const DownloadModal = () => (
    <div className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center z-50">
      <div className="bg-white p-6 rounded-xl shadow-2xl max-w-md w-full mx-4 relative">
        {/* 右上角关闭按钮 */}
        <button
          onClick={() => setIsDownloadModalOpen(false)}
          className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition-colors"
        >
          <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12"></path>
          </svg>
        </button>

        <div className="text-center space-y-4 pt-2">
          <h3 className="text-xl font-bold text-gray-800">
            {downloadMessage}
          </h3>
          <p className="text-sm text-gray-600">
            点击下方按钮开始下载：
          </p>

          <div className="pt-4">
            <a
              href={downloadUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="block w-full px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 text-center"
            >
              点击下载发票
            </a>
          </div>

          <div className="pt-2">
            <button
              onClick={() => setIsDownloadModalOpen(false)}
              className="px-6 py-2 bg-gray-200 hover:bg-gray-300 text-gray-800 rounded-lg"
            >
              关闭
            </button>
          </div>
        </div>
      </div>
    </div>
  );

  // 修改：添加获取输入框样式的函数
  const getInputClass = (fieldName: string) => {
    const baseClass = "w-full px-4 py-2 border rounded-md";
    return validationErrors[fieldName]
      ? `${baseClass} border-red-500 bg-red-50`
      : `${baseClass} border-gray-300`;
  };

  // 修改：添加获取选择框样式的函数
  const getSelectClass = (fieldName: string) => {
    const baseClass = "w-full px-4 py-2 border rounded-md";
    return validationErrors[fieldName]
      ? `${baseClass} border-red-500 bg-red-50`
      : `${baseClass} border-gray-300`;
  };

  return (
    <main className="min-h-screen">
      <section className="py-20 pt-8">
        <div className="container mx-auto px-4">
          <div className="max-w-5xl mx-auto">
            <div className="bg-white rounded-lg shadow-sm p-8">
              <h2 className="text-2xl font-bold mb-6 text-center">个人发票开具</h2>

              <form className="space-y-6">
                {/* 购方和销方信息 - 左右布局 */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                  {/* 购方信息 - 左侧 */}
                  <div className="space-y-4">
                    <h3 className="text-lg font-medium border-b pb-2">购方信息</h3>
                    <div>
                      <label className="block text-sm font-medium mb-1">
                        购方名称 <span className="text-red-600">*</span>
                      </label>
                      <input
                        type="text"
                        name="ghdwmc"
                        value={formData.ghdwmc}
                        onChange={handleInputChange}
                        className={getInputClass("ghdwmc")}
                        placeholder="请输入购方名称"
                        required
                      />
                      {validationErrors.ghdwmc && (
                        <p className="mt-1 text-sm text-red-600">请填写购方名称</p>
                      )}
                    </div>
                    {/* <div>
                      <label className="block text-sm font-medium mb-1">购方电话</label>
                      <input
                        type="text"
                        name="ghdwdh"
                        value={formData.ghdwdh}
                        onChange={handleInputChange}
                        className="w-full px-4 py-2 border rounded-md"
                        placeholder="请输入联系电话"
                      />
                    </div> */}
                    <div>
                      <label className="block text-sm font-medium mb-1">
                        购方电话<span className="text-red-600">*</span>
                      </label>
                      <input
                        type="text"
                        name="ghdwdh"
                        value={formData.ghdwdh}
                        onChange={handleInputChange}
                        className={getInputClass("ghdwdh")}
                        placeholder="请输入联系电话"
                      />
                      {validationErrors.ghdwdh && (
                        <p className="mt-1 text-sm text-red-600">请输入联系电话</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1">
                        统一社会信用代码/纳税人识别号<span className="text-red-600">*</span>
                      </label>
                      <input
                        type="text"
                        name="ghdwsbh"
                        value={formData.ghdwsbh}
                        onChange={handleInputChange}
                        className={getInputClass("ghdwsbh")}
                        placeholder="请输入统一社会信用代码"
                      />
                      {validationErrors.ghdwsbh && (
                        <p className="mt-1 text-sm text-red-600">请填写纳税人识别号</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1">购方地址</label>
                      <input
                        type="text"
                        name="ghdwdz"
                        value={formData.ghdwdz}
                        onChange={handleInputChange}
                        className="w-full px-4 py-2 border rounded-md"
                        placeholder="请输入购方地址"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium mb-1">购方银行</label>
                      <input
                        type="text"
                        name="ghdwyh"
                        value={formData.ghdwyh}
                        onChange={handleInputChange}
                        className="w-full px-4 py-2 border rounded-md"
                        placeholder="请输入开户银行"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1">购方账号</label>
                      <input
                        type="text"
                        name="ghdwzh"
                        value={formData.ghdwzh}
                        onChange={handleInputChange}
                        className="w-full px-4 py-2 border rounded-md"
                        placeholder="请输入银行账号"
                      />
                    </div>
                  </div>

                  {/* 销方信息 - 右侧 */}
                  <div className="space-y-4">
                    <h3 className="text-lg font-medium border-b pb-2">销方信息</h3>
                    <div>
                      <label className="block text-sm font-medium mb-1">
                        销方名称 <span className="text-red-600">*</span>
                      </label>
                      <input
                        type="text"
                        value="中税师（北京）税务咨询中心"
                        readOnly
                        className="w-full px-4 py-2 border rounded-md bg-gray-100"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1">
                        统一社会信用代码/纳税人识别号 <span className="text-red-600">*</span>
                      </label>
                      <input
                        type="text"
                        value="91110108802079937H"
                        readOnly
                        className="w-full px-4 py-2 border rounded-md bg-gray-100"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1">
                        销方银行 <span className="text-red-600">*</span>
                      </label>
                      <input
                        type="text"
                        value="中国农业银行股份有限公司北京古城支行"
                        readOnly
                        className="w-full px-4 py-2 border rounded-md bg-gray-100"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1">
                        销方账号 <span className="text-red-600">*</span>
                      </label>
                      <input
                        type="text"
                        value="11031301040052826"
                        readOnly
                        className="w-full px-4 py-2 border rounded-md bg-gray-100"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1">
                        销方电话 <span className="text-red-600">*</span>
                      </label>
                      <input
                        type="text"
                        value="010-68814900"
                        readOnly
                        className="w-full px-4 py-2 border rounded-md bg-gray-100"
                      />
                    </div>
                  </div>
                </div>

                {/* 发票基本信息 */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mt-6">
                  <div>
                    <label className="block text-sm font-medium mb-1">发票类型<span className="text-red-600">*</span></label>
                    <select
                      name="fplxdm"
                      value={formData.fplxdm}
                      onChange={handleInputChange}
                      className={getSelectClass("fplxdm")}
                      required
                    >
                      <option value="">请选择发票类型</option>
                      <option value="81">数电专票</option>
                      <option value="82">数电普票</option>
                    </select>
                    {validationErrors.fplxdm && (
                      <p className="mt-1 text-sm text-red-600">请选择发票类型</p>
                    )}
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-1">开票类型<span className="text-red-600">*</span></label>
                    <select
                      name="kplx"
                      value={formData.kplx}
                      onChange={handleInputChange}
                      className={getSelectClass("kplx")}
                      required
                    >
                      <option value="">请选择开票类型</option>
                      <option value="0">正数发票开具</option>
                      <option value="1">负数发票开具（红冲）</option>
                    </select>
                    {validationErrors.kplx && (
                      <p className="mt-1 text-sm text-red-600">请选择开票类型</p>
                    )}
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-1">开票人<span className="text-red-600">*</span></label>
                    <input
                      type="text"
                      name="kpr"
                      value={formData.kpr}
                      onChange={handleInputChange}
                      className={getInputClass("kpr")}
                      placeholder="请输入开票人姓名"
                      required
                    />
                    {validationErrors.kpr && (
                      <p className="mt-1 text-sm text-red-600">请填写开票人</p>
                    )}
                  </div>
                </div>

                {/* 发票明细 */}
                <div className="mt-8">
                  <div className="flex justify-between items-center mb-4">
                    <h3 className="text-lg font-medium">发票明细 <span className="text-red-600">*</span></h3>
                    <button
                      type="button"
                      onClick={addNewItem}
                      className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700"
                    >
                      添加行
                    </button>
                  </div>

                  {invoiceItems.map((item, index) => (
                    <div key={index} className="border border-gray-200 p-4 rounded-md mb-4 relative">
                      {invoiceItems.length > 1 && (
                        <button
                          type="button"
                          onClick={() => removeItem(index)}
                          className="absolute top-2 right-2 text-red-600 hover:text-red-800"
                          title="删除此行"
                        >
                          ×
                        </button>
                      )}

                      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div>
                          <label className="block text-sm font-medium mb-1">序号</label>
                          <input
                            type="text"
                            value={item.xh}  // 使用行项目自身的xh值
                            readOnly
                            className="w-full px-4 py-2 border rounded-md bg-gray-100"
                          />
                        </div>
                        <div>
                          <label className="block text-sm font-medium mb-1">含税标志</label>
                          <select
                            value={formData.hsbz}
                            onChange={(e) => handleItemChange(index, 'hsbz', e.target.value)}
                            className="w-full px-4 py-2 border rounded-md"
                          >
                            <option value="1">含税</option>
                            <option value="0">不含税</option>
                          </select>
                        </div>
                        <div>
                          <label className="block text-sm font-medium mb-1">项目名称 <span className="text-red-600">*</span></label>
                          <input
                            type="text"
                            value="*非学历教育服务*培训费"
                            readOnly
                            className="w-full px-4 py-2 border rounded-md bg-gray-100"
                          />
                        </div>
                        <div>
                          <label className="block text-sm font-medium mb-1">金额 <span className="text-red-600">*</span></label>
                          <input
                            type="text"
                            value="2298"
                            readOnly
                            className="w-full px-4 py-2 border rounded-md bg-gray-100"
                          />
                        </div>
                        <div>
                          <label className="block text-sm font-medium mb-1">税率</label>
                          <select
                            value={formData.sl}
                            onChange={(e) => handleItemChange(index, 'sl', e.target.value)}
                            className="w-full px-4 py-2 border rounded-md"
                          >
                            <option value="0.01">1%</option>
                            <option value="0.03">3%</option>
                            <option value="0.06">6%</option>

                          </select>
                        </div>
                        <div>
                          <label className="block text-sm font-medium mb-1">税额</label>
                          <input
                            type="text"
                            name="se"
                            value={formData.se}
                            readOnly
                            className="w-full px-4 py-2 border rounded-md bg-gray-100"
                          />
                        </div>
                        <div>
                          <label className="block text-sm font-medium mb-1">商品编码</label>
                          <input
                            type="text"
                            name="spbm"
                            value="307020102"
                            onChange={handleInputChange}
                            className="w-full px-4 py-2 border rounded-md"
                            readOnly
                          />
                        </div>
                        <div>
                          <label className="block text-sm font-medium mb-1">发票行性质</label>
                          <select
                            value={formData.fphxz}
                            onChange={(e) => handleItemChange(index, 'fphxz', e.target.value)}
                            className="w-full px-4 py-2 border rounded-md"
                          >
                            <option value="0">正常行</option>
                            {/* <option value="1">折扣行</option>
                            <option value="2">被折扣行</option> */}
                          </select>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>

                {/* 合计信息 */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mt-6 bg-gray-50 p-4 rounded-md">
                  <div>
                    <label className="block text-sm font-medium mb-1">合计金额</label>
                    <input
                      type="text"
                      name="hjje"
                      value={formData.hjje}
                      readOnly
                      className="w-full px-4 py-2 border rounded-md bg-white font-semibold"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-1">合计税额</label>
                    <input
                      type="text"
                      name="hjse"
                      value={formData.hjse}
                      readOnly
                      className="w-full px-4 py-2 border rounded-md bg-white font-semibold"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-1">价税合计</label>
                    <input
                      type="text"
                      name="jshj"
                      value={formData.jshj}
                      readOnly
                      className="w-full px-4 py-2 border rounded-md bg-white font-semibold"
                    />
                  </div>
                  <div className="md:col-span-3">
                    <label className="block text-sm font-medium mb-1">价税合计（大写）</label>
                    <div className="w-full px-4 py-2 border border-gray-300 rounded-md bg-white min-h-[42px] font-semibold">
                      {formData.jshjdx}
                    </div>
                  </div>
                </div>

                {/* 备注 */}
                <div className="mt-6">
                  <label className="block text-sm font-medium mb-1">备注</label>
                  <input
                    type="text"
                    name="bz"
                    value={formData.bz}
                    onChange={handleInputChange}
                    className="w-full px-4 py-2 border rounded-md"
                    placeholder="请输入备注信息"
                  />
                </div>

                {/* 提交按钮 */}
                <div className="mt-8">
                  {hasDownloadableInvoice ? (
                    <button
                      onClick={() => window.open(downloadUrl, '_blank')}
                      className="w-full py-3 px-4 rounded-md text-white font-medium bg-green-600 hover:bg-green-700"
                    >
                      <svg className="inline-block mr-2 w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                      </svg>
                      下载发票
                    </button>
                  ) : (
                    <button
                      type="button"
                      onClick={submitFormData1}
                      className="w-full py-3 px-4 rounded-md text-white font-medium bg-blue-600 hover:bg-blue-700"
                    >
                      {isSubmitting ? "提交中..." : "提交发票信息"}
                    </button>
                  )}
                </div>
              </form>
            </div>
          </div>
        </div>
      </section>

      {/* 成功弹窗 */}
      {isSuccessModalOpen && successData && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center z-50">
          <div className="bg-white p-6 rounded-xl shadow-2xl max-w-md w-full mx-4">
            <div className="text-center space-y-4">
              <h3 className="text-xl font-bold text-gray-800">发票开具成功</h3>
              <div className="text-left space-y-2">
                <p><span className="font-medium">发票号码:</span> {successData.fphm}</p>
                <p><span className="font-medium">开票日期:</span> {successData.kprq}</p>
              </div>
              <div className="grid grid-cols-2 gap-3 pt-4">
                <button
                  onClick={() => handleDownload(successData.pdfUrl, 'PDF')}
                  className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg"
                >
                  下载PDF
                </button>
                <button
                  onClick={() => handleDownload(successData.ofdUrl, 'OFD')}
                  className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg"
                >
                  下载OFD
                </button>
                <button
                  onClick={() => handleViewQrCode(successData.ewmUrl)}
                  className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg col-span-2"
                >
                  查看电子票二维码
                </button>
              </div>
              <h3>温馨提示：</h3>
              <p className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg">手机端请在手机文件中查看所下载发票可传出到文件助手内使用！</p>
              <p className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg">电脑端请在浏览器下载历史中查看所下载发票！</p>
              <div className="pt-4">
                <button
                  onClick={() => setIsSuccessModalOpen(false)}
                  className="px-6 py-2 bg-gray-200 hover:bg-gray-300 text-gray-800 rounded-lg"
                >
                  关闭
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
      {/* 显示二维码图片 */}
      {qrCodeBase64 && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center z-50 animate-fadeIn">
          <div className="bg-white p-6 rounded-xl shadow-2xl max-w-md w-full mx-4 border border-gray-100 animate-scaleIn">
            <div className="text-center space-y-4">
              <h3 className="text-xl font-bold text-gray-800">
                首次开票认证
              </h3>
              <p className="text-sm text-gray-600">
                请开票人员使用<b>电子税务局APP</b>扫描下方二维码进行人脸识别
              </p>

              {/* 二维码容器 */}
              <div className="p-4 bg-white rounded-lg border-2 border-gray-100 shadow-sm inline-flex">
                <img
                  src={`data:image/png;base64,${qrCodeBase64}`}
                  alt="认证二维码"
                  className="w-48 h-48 object-contain mx-auto"
                />
              </div>

              {/* 操作按钮 */}
              <div className="pt-2">
                <button
                  onClick={handleQrCodeClose}
                  className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
                >
                  完成认证
                </button>
              </div>

              {/* 辅助提示 */}
              <p className="text-xs text-gray-500 mt-2">
                认证成功后系统将自动继续开票流程
              </p>
            </div>
          </div>
        </div>
      )}

      {/* 新增：下载发票弹窗 */}
      {isDownloadModalOpen && downloadUrl && (
        <DownloadModal />
      )}

      {submitError && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
          <strong className="font-bold">错误:</strong>
          <span className="block sm:inline">{submitError}</span>
        </div>
      )}

      {/* 提示弹窗 */}
      {isAlertOpen && <AlertModal />}
    </main>
  );
}

export default function CertificatesPage() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <InvoiceForm />
    </Suspense>
  );
}